package com.hgxd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hgxd.entity.pojo.SlaveHistory;
import com.hgxd.entity.pojo.SlaveLinkGroup;
import com.hgxd.entity.req.ReqSlaveGroup;
import com.hgxd.entity.vo.SlaveSimpleVo;
import com.hgxd.exception.ServiceException;
import com.hgxd.mapper.SlaveLinkGroupMapper;
import com.hgxd.result.ResultCodeEnum;
import com.hgxd.service.ISlaveHistoryService;
import com.hgxd.service.ISlaveLinkGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 从机和从机分组关联表 服务实现类
 * </p>
 *
 * @author wtf
 * @since 2024-09-02
 */
@Service("SlaveLinkGroupServiceImpl")
public class SlaveLinkGroupServiceImpl extends ServiceImpl<SlaveLinkGroupMapper, SlaveLinkGroup> implements ISlaveLinkGroupService {

    @Resource
    private SlaveLinkGroupMapper slaveLinkGroupMapper;

    @Resource(name = "SlaveHistoryServiceImpl")
    private ISlaveHistoryService slaveHistoryService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveSlaveGroups(ReqSlaveGroup slaveGroup) {
        // 查询该组下的所有从机id
        // 数据库中的从机id集合
        List<Integer> sqlList = getSlaveIdBySlaveGroupId(slaveGroup.getSlaveGroupId());
        // 用户提供的从机id集合
        List<Integer> userList = slaveGroup.getSimpleSlaves().stream()
                .map(SlaveSimpleVo::getSlaveId).collect(Collectors.toList());
        if (! checkElements(userList, sqlList)){
            throw new ServiceException(ResultCodeEnum.DATA_ERROR,"有重复数据添加");
        }
        return saveSlaveGroupsByXml(slaveGroup);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateSlaveGroups(ReqSlaveGroup slaveGroup) {
        // 1.先删除旧的关联关系
        deleteSlaveGroupBySlaveGroupId(slaveGroup.getSlaveGroupId());
        // 2.再添加新的关联关系
        saveSlaveGroupsByXml(slaveGroup);
        return true;
    }

    @Override
    public Boolean deleteBySlaveGroupsId(Integer slaveGroupId) {
        return deleteSlaveGroupBySlaveGroupId(slaveGroupId);
    }

    @Override
    public List<SlaveHistory> getSlaveMessageByGroupId(Integer slaveGroupId) {
//        long a = System.currentTimeMillis();
        // 1.先根据slaveGroupId查询其下的所有从机数据（slaveIds）
        List<Integer> slaveIds = getSlaveIdBySlaveGroupId(slaveGroupId);
//        System.out.println("查询从机查询耗时：" + (System.currentTimeMillis() - a));
        // 2.根据slaveId查询对应从机的最新数据
        List<SlaveHistory> list = new ArrayList<>();
        for (Integer slaveId : slaveIds) {
            SlaveHistory slaveHistory = slaveHistoryService.getNewSlaveMessageBySlaveId(slaveId);
            list.add(slaveHistory);
        }
//        System.out.println("总查询耗时：" + (System.currentTimeMillis() - a));
        return list;
    }

    @Override
    public Boolean deleteBySlaveId(Integer slaveId) {
        return deleteSlaveGroupBySlaveId(slaveId);
    }


    /**
     * 根据slaveId删除关联关系
     * @param slaveId
     * @return
     */
    private Boolean deleteSlaveGroupBySlaveId(Integer slaveId){
        LambdaQueryWrapper<SlaveLinkGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SlaveLinkGroup::getSlaveId,slaveId);
        int delete = slaveLinkGroupMapper.delete(queryWrapper);
        if (delete <= 0) {
            throw new ServiceException(ResultCodeEnum.SERVICE_ERROR, "删除失败");
        }
        return true;
    }

    /**
     * 根据slaveGroupId获取其下的slaveId
     * @param slaveGroupId
     * @return
     */
    private List<Integer> getSlaveIdBySlaveGroupId(Integer slaveGroupId) {
        LambdaQueryWrapper<SlaveLinkGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SlaveLinkGroup::getSlaveGroupId, slaveGroupId);
        List<SlaveLinkGroup> slaveLinkGroups = slaveLinkGroupMapper.selectList(queryWrapper);
        return slaveLinkGroups.stream().map(SlaveLinkGroup::getSlaveId)
                .collect(Collectors.toList());
    }


    /**
     * 增加从机和组的关联关系
     * @param slaveGroup
     * @return
     */
    private Boolean saveSlaveGroupsByXml(ReqSlaveGroup slaveGroup) {
        Boolean a = slaveLinkGroupMapper.saveSlaveGroups(slaveGroup);
        if (!a) {
            throw new ServiceException(ResultCodeEnum.SERVICE_ERROR, "添加失败");
        }
        return true;
    }

    /**
     * 根据groupId删除关联关系
     * @param slaveGroupId
     * @return
     */
    private Boolean deleteSlaveGroupBySlaveGroupId(Integer slaveGroupId){
        LambdaQueryWrapper<SlaveLinkGroup> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SlaveLinkGroup::getSlaveGroupId, slaveGroupId);
        int delete = slaveLinkGroupMapper.delete(queryWrapper);
        if (delete <= 0) {
            throw new ServiceException(ResultCodeEnum.SERVICE_ERROR, "删除失败");
        }
        return true;
    }


    /**
     * 判断集合A中的元素是否存在集合B中
     * @param listA
     * @param listB
     * @return 如果存在，返回false，不存在返回true
     */
    public static boolean checkElements(List<Integer> listA, List<Integer> listB) {
        HashSet<Integer> setB = new HashSet<>(listB);

        for (Integer element : listA) {
            if (setB.contains(element)) {
                return false;
            }
        }
        return true;
    }




}
